{
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "ur8xi4C7S06n"
      },
      "outputs": [],
      "source": [
        "# Copyright 2021 Google LLC\n",
        "#\n",
        "# Licensed under the Apache License, Version 2.0 (the \"License\");\n",
        "# you may not use this file except in compliance with the License.\n",
        "# You may obtain a copy of the License at\n",
        "#\n",
        "#     https://www.apache.org/licenses/LICENSE-2.0\n",
        "#\n",
        "# Unless required by applicable law or agreed to in writing, software\n",
        "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
        "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
        "# See the License for the specific language governing permissions and\n",
        "# limitations under the License."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "JAPoU8Sm5E6e"
      },
      "source": [
        "<table align=\"left\">\n",
        "\n",
        "  <td>\n",
        "    <a href=\"https://colab.research.google.com/github/GoogleCloudPlatform/vertex-ai-samples/blob/master/notebooks/official/feature_store/gapic-feature-store.ipynb\"\">\n",
        "      <img src=\"https://cloud.google.com/ml-engine/images/colab-logo-32px.png\" alt=\"Colab logo\"> Run in Colab\n",
        "    </a>\n",
        "  </td>\n",
        "  <td>\n",
        "    <a href=\"https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/master/notebooks/official/feature_store/gapic-feature-store.ipynb\">\n",
        "      <img src=\"https://cloud.google.com/ml-engine/images/github-logo-32px.png\" alt=\"GitHub logo\">\n",
        "      View on GitHub\n",
        "    </a>\n",
        "  </td>\n",
        "</table>"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "tvgnzT1CKxrO"
      },
      "source": [
        "## Overview\n",
        "\n",
        "This Colab introduces Feature Store, a managed cloud service for machine learning engineers and data scientists to store, serve, manage and share machine learning features at a large scale.\n",
        "\n",
        "This Colab assumes that you understand basic Google Cloud concepts such as [Project](https://cloud.google.com/storage/docs/projects), [Storage](https://cloud.google.com/storage) and [Vertex AI](https://cloud.google.com/vertex-ai/docs). Some machine learning knowledge is also helpful but not required.\n",
        "\n",
        "### Dataset\n",
        "\n",
        "This Colab uses a movie recommendation dataset as an example throughout all the sessions. The task is to train a model to predict if a user is going to watch a movie and serve this model online. \n",
        "\n",
        "### Objective\n",
        "\n",
        "In this notebook, you will learn how to:\n",
        "\n",
        "    * How to import your features into Feature Store.\n",
        "    * How to serve online prediction requests using the imported features.\n",
        "    * How to access imported features in offline jobs, such as training jobs.\n",
        "\n",
        "### Costs \n",
        "\n",
        "This tutorial uses billable components of Google Cloud:\n",
        "\n",
        "* Vertex AI\n",
        "* Cloud Storage\n",
        "* Cloud Bigtable\n",
        "\n",
        "Learn about [Vertex AI\n",
        "pricing](https://cloud.google.com/vertex-ai/pricing) and [Cloud Storage\n",
        "pricing](https://cloud.google.com/storage/pricing), and use the [Pricing\n",
        "Calculator](https://cloud.google.com/products/calculator/)\n",
        "to generate a cost estimate based on your projected usage."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "ze4-nDLfK4pw"
      },
      "source": [
        "### Set up your local development environment\n",
        "\n",
        "**If you are using Colab or Google Cloud Notebooks**, your environment already meets\n",
        "all the requirements to run this notebook. You can skip this step."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "gCuSR8GkAgzl"
      },
      "source": [
        "**Otherwise**, make sure your environment meets this notebook's requirements.\n",
        "You need the following:\n",
        "\n",
        "* The Google Cloud SDK\n",
        "* Git\n",
        "* Python 3\n",
        "* virtualenv\n",
        "* Jupyter notebook running in a virtual environment with Python 3\n",
        "\n",
        "The Google Cloud guide to [Setting up a Python development\n",
        "environment](https://cloud.google.com/python/setup) and the [Jupyter\n",
        "installation guide](https://jupyter.org/install) provide detailed instructions\n",
        "for meeting these requirements. The following steps provide a condensed set of\n",
        "instructions:\n",
        "\n",
        "1. [Install and initialize the Cloud SDK.](https://cloud.google.com/sdk/docs/)\n",
        "\n",
        "1. [Install Python 3.](https://cloud.google.com/python/setup#installing_python)\n",
        "\n",
        "1. [Install\n",
        "   virtualenv](https://cloud.google.com/python/setup#installing_and_using_virtualenv)\n",
        "   and create a virtual environment that uses Python 3. Activate the virtual environment.\n",
        "\n",
        "1. To install Jupyter, run `pip install jupyter` on the\n",
        "command-line in a terminal shell.\n",
        "\n",
        "1. To launch Jupyter, run `jupyter notebook` on the command-line in a terminal shell.\n",
        "\n",
        "1. Open this notebook in the Jupyter Notebook Dashboard."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "i7EUnXsZhAGF"
      },
      "source": [
        "### Install additional packages\n",
        "\n",
        "For this Colab, you need the Vertex SDK for Python."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "2b4ef9b72d43"
      },
      "outputs": [],
      "source": [
        "import os\n",
        "\n",
        "# The Google Cloud Notebook product has specific requirements\n",
        "IS_GOOGLE_CLOUD_NOTEBOOK = os.path.exists(\"/opt/deeplearning/metadata/env_version\")\n",
        "\n",
        "# Google Cloud Notebook requires dependencies to be installed with '--user'\n",
        "USER_FLAG = \"\"\n",
        "if IS_GOOGLE_CLOUD_NOTEBOOK:\n",
        "    USER_FLAG = \"--user\""
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "wyy5Lbnzg5fi"
      },
      "outputs": [],
      "source": [
        "! pip install {USER_FLAG} --upgrade git+https://github.com/googleapis/python-aiplatform.git@main-test"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "hhq5zEbGg0XX"
      },
      "source": [
        "### Restart the kernel\n",
        "\n",
        "After you install the SDK, you need to restart the notebook kernel so it can find the packages. You can restart kernel from *Kernel -> Restart Kernel*, or running the following:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "EzrelQZ22IZj"
      },
      "outputs": [],
      "source": [
        "# Automatically restart kernel after installs\n",
        "import os\n",
        "\n",
        "if not os.getenv(\"IS_TESTING\"):\n",
        "    # Automatically restart kernel after installs\n",
        "    import IPython\n",
        "\n",
        "    app = IPython.Application.instance()\n",
        "    app.kernel.do_shutdown(True)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "lWEdiXsJg0XY"
      },
      "source": [
        "## Before you begin\n",
        "\n",
        "### Select a GPU runtime\n",
        "\n",
        "**Make sure you're running this notebook in a GPU runtime if you have that option. In Colab, select \"Runtime --> Change runtime type > GPU\"**"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "BF1j6f9HApxa"
      },
      "source": [
        "### Set up your Google Cloud project\n",
        "\n",
        "**The following steps are required, regardless of your notebook environment.**\n",
        "\n",
        "1. [Select or create a Google Cloud project](https://console.cloud.google.com/cloud-resource-manager). When you first create an account, you get a $300 free credit towards your compute/storage costs.\n",
        "\n",
        "1. [Make sure that billing is enabled for your project](https://cloud.google.com/billing/docs/how-to/modify-project).\n",
        "\n",
        "1. [Enable the Vertex AI API and Compute Engine API](https://console.cloud.google.com/flows/enableapi?apiid=aiplatform.googleapis.com,compute_component).\n",
        "\n",
        "1. If you are running this notebook locally, you will need to install the [Cloud SDK](https://cloud.google.com/sdk).\n",
        "\n",
        "1. Enter your project ID in the cell below. Then run the cell to make sure the\n",
        "Cloud SDK uses the right project for all the commands in this notebook.\n",
        "\n",
        "**Note**: Jupyter runs lines prefixed with `!` as shell commands, and it interpolates Python variables prefixed with `$` into these commands."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "WReHDGG5g0XY"
      },
      "source": [
        "#### Set your project ID\n",
        "\n",
        "**If you don't know your project ID**, you may be able to get your project ID using `gcloud`."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "oM1iC_MfAts1"
      },
      "outputs": [],
      "source": [
        "import os\n",
        "\n",
        "PROJECT_ID = \"\"\n",
        "\n",
        "# Get your Google Cloud project ID from gcloud\n",
        "if not os.getenv(\"IS_TESTING\"):\n",
        "    shell_output=!gcloud config list --format 'value(core.project)' 2>/dev/null\n",
        "    PROJECT_ID = shell_output[0]\n",
        "    print(\"Project ID: \", PROJECT_ID)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "qJYoRfYng0XZ"
      },
      "source": [
        "Otherwise, set your project ID here."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "riG_qUokg0XZ"
      },
      "outputs": [],
      "source": [
        "if PROJECT_ID == \"\" or PROJECT_ID is None:\n",
        "    PROJECT_ID = \"python-docs-samples-tests\"  # @param {type:\"string\"}"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "dr--iN2kAylZ"
      },
      "source": [
        "### Authenticate your Google Cloud account\n",
        "\n",
        "**If you are using Google Cloud Notebooks**, your environment is already\n",
        "authenticated. Skip this step."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "sBCra4QMA2wR"
      },
      "source": [
        "**If you are using Colab**, run the cell below and follow the instructions\n",
        "when prompted to authenticate your account via oAuth.\n",
        "\n",
        "**Otherwise**, follow these steps:\n",
        "\n",
        "1. In the Cloud Console, go to the [**Create service account key**\n",
        "   page](https://console.cloud.google.com/apis/credentials/serviceaccountkey).\n",
        "\n",
        "2. Click **Create service account**.\n",
        "\n",
        "3. In the **Service account name** field, enter a name, and\n",
        "   click **Create**.\n",
        "\n",
        "4. In the **Grant this service account access to project** section, click the **Role** drop-down list. Type \"Vertex AI\"\n",
        "into the filter box, and select\n",
        "   **Vertex AI Administrator**. Type \"Storage Object Admin\" into the filter box, and select **Storage Object Admin**.\n",
        "\n",
        "5. Click *Create*. A JSON file that contains your key downloads to your\n",
        "local environment.\n",
        "\n",
        "6. Enter the path to your service account key as the\n",
        "`GOOGLE_APPLICATION_CREDENTIALS` variable in the cell below and run the cell."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "PyQmSRbKA8r-"
      },
      "outputs": [],
      "source": [
        "import os\n",
        "import sys\n",
        "\n",
        "# If you are running this notebook in Colab, run this cell and follow the\n",
        "# instructions to authenticate your GCP account. This provides access to your\n",
        "# Cloud Storage bucket and lets you submit training jobs and prediction\n",
        "# requests.\n",
        "\n",
        "# The Google Cloud Notebook product has specific requirements\n",
        "IS_GOOGLE_CLOUD_NOTEBOOK = os.path.exists(\"/opt/deeplearning/metadata/env_version\")\n",
        "\n",
        "# If on Google Cloud Notebooks, then don't execute this code\n",
        "if not IS_GOOGLE_CLOUD_NOTEBOOK:\n",
        "    if \"google.colab\" in sys.modules:\n",
        "        from google.colab import auth as google_auth\n",
        "\n",
        "        google_auth.authenticate_user()\n",
        "\n",
        "    # If you are running this notebook locally, replace the string below with the\n",
        "    # path to your service account key and run this cell to authenticate your GCP\n",
        "    # account.\n",
        "    elif not os.getenv(\"IS_TESTING\"):\n",
        "        %env GOOGLE_APPLICATION_CREDENTIALS ''"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "gAL9Y4VTOLT1"
      },
      "source": [
        "## Prepare for output\n",
        "\n",
        "### Step 1. Create dataset for output\n",
        "\n",
        "You need a BigQuery dataset to host the output data in `us-central1`. Input the name of the dataset you want to created and specify the name of the table you want to store the output later. These will be used later in the notebook.\n",
        "\n",
        "**Make sure that the table name does NOT already exist**.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "4Oc-jrd6Ow7N"
      },
      "outputs": [],
      "source": [
        "from datetime import datetime\n",
        "\n",
        "from google.cloud import bigquery"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "QOaGi2PrEAwA"
      },
      "outputs": [],
      "source": [
        "# Output dataset\n",
        "DESTINATION_DATA_SET = \"movie_predictions\"  # @param {type:\"string\"}\n",
        "TIMESTAMP = datetime.now().strftime(\"%Y%m%d%H%M%S\")\n",
        "DESTINATION_DATA_SET = \"{prefix}_{timestamp}\".format(\n",
        "    prefix=DESTINATION_DATA_SET, timestamp=TIMESTAMP\n",
        ")\n",
        "\n",
        "# Output table. Make sure that the table does NOT already exist; the BatchReadFeatureValues API cannot overwrite an existing table\n",
        "DESTINATION_TABLE_NAME = \"training_data\"  # @param {type:\"string\"}\n",
        "\n",
        "DESTINATION_PATTERN = \"bq://{project}.{dataset}.{table}\"\n",
        "DESTINATION_TABLE_URI = DESTINATION_PATTERN.format(\n",
        "    project=PROJECT_ID, dataset=DESTINATION_DATA_SET, table=DESTINATION_TABLE_NAME\n",
        ")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "RKhmymT-O0vy"
      },
      "outputs": [],
      "source": [
        "# Create dataset\n",
        "REGION = \"us-central1\"  # @param {type:\"string\"}\n",
        "client = bigquery.Client()\n",
        "dataset_id = \"{}.{}\".format(client.project, DESTINATION_DATA_SET)\n",
        "dataset = bigquery.Dataset(dataset_id)\n",
        "dataset.location = REGION\n",
        "dataset = client.create_dataset(dataset, timeout=30)\n",
        "print(\"Created dataset {}.{}\".format(client.project, dataset.dataset_id))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "XoEqT2Y4DJmf"
      },
      "source": [
        "### Import libraries and define constants"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "isNzmylQXjly"
      },
      "outputs": [],
      "source": [
        "# Other than project ID and featurestore ID and endpoints needs to be set\n",
        "API_ENDPOINT = \"us-central1-aiplatform.googleapis.com\"  # @param {type:\"string\"}\n",
        "INPUT_CSV_FILE = \"gs://cloud-samples-data-us-central1/ai-platform-unified/datasets/featurestore/movie_prediction.csv\""
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "pRUOFELefqf1"
      },
      "outputs": [],
      "source": [
        "from google.cloud.aiplatform_v1beta1 import (\n",
        "    FeaturestoreOnlineServingServiceClient, FeaturestoreServiceClient)\n",
        "from google.cloud.aiplatform_v1beta1.types import FeatureSelector, IdMatcher\n",
        "from google.cloud.aiplatform_v1beta1.types import \\\n",
        "    entity_type as entity_type_pb2\n",
        "from google.cloud.aiplatform_v1beta1.types import feature as feature_pb2\n",
        "from google.cloud.aiplatform_v1beta1.types import \\\n",
        "    featurestore as featurestore_pb2\n",
        "from google.cloud.aiplatform_v1beta1.types import \\\n",
        "    featurestore_monitoring as featurestore_monitoring_pb2\n",
        "from google.cloud.aiplatform_v1beta1.types import \\\n",
        "    featurestore_online_service as featurestore_online_service_pb2\n",
        "from google.cloud.aiplatform_v1beta1.types import \\\n",
        "    featurestore_service as featurestore_service_pb2\n",
        "from google.cloud.aiplatform_v1beta1.types import io as io_pb2\n",
        "from google.protobuf.duration_pb2 import Duration\n",
        "\n",
        "# Create admin_client for CRUD and data_client for reading feature values.\n",
        "admin_client = FeaturestoreServiceClient(client_options={\"api_endpoint\": API_ENDPOINT})\n",
        "data_client = FeaturestoreOnlineServingServiceClient(\n",
        "    client_options={\"api_endpoint\": API_ENDPOINT}\n",
        ")\n",
        "\n",
        "# Represents featurestore resource path.\n",
        "BASE_RESOURCE_PATH = admin_client.common_location_path(PROJECT_ID, REGION)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "h_HmF24mBHv9"
      },
      "source": [
        "## Terminology and Concept\n",
        "\n",
        "### Featurestore Data model\n",
        "\n",
        "Feature Store organizes data with the following 3 important hierarchical concepts:\n",
        "```\n",
        "Featurestore -> EntityType -> Feature\n",
        "```\n",
        "* **Featurestore**: the place to store your features\n",
        "* **EntityType**: under a Featurestore, an *EntityType* describes an object to be modeled, real one or virtual one.\n",
        "* **Feature**: under an EntityType, a *feature* describes an attribute of the EntityType\n",
        "\n",
        "In the movie prediction example, you will create a featurestore called *movie_prediction*. This store has 2 entity types: *Users* and *Movies*. The Users entity type has the age, gender, and like genres features. The Movies entity type has the genres and average rating features.\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "9UvxYyGUimKw"
      },
      "source": [
        "## Create Featurestore and Define Schemas"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "buQBIv3ZL3A0"
      },
      "source": [
        "### Create Featurestore\n",
        "\n",
        "The method to create a featurestore returns a\n",
        "[long-running operation](https://google.aip.dev/151) (LRO). An LRO starts an asynchronous job. LROs are returned for other API\n",
        "methods too, such as updating or deleting a featurestore. Calling\n",
        "`create_fs_lro.result()` waits for the LRO to complete."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "FscHZa0DXjmC"
      },
      "outputs": [],
      "source": [
        "FEATURESTORE_ID = \"movie_prediction_{timestamp}\".format(timestamp=TIMESTAMP)\n",
        "create_lro = admin_client.create_featurestore(\n",
        "    featurestore_service_pb2.CreateFeaturestoreRequest(\n",
        "        parent=BASE_RESOURCE_PATH,\n",
        "        featurestore_id=FEATURESTORE_ID,\n",
        "        featurestore=featurestore_pb2.Featurestore(\n",
        "            display_name=\"Featurestore for movie prediction\",\n",
        "            online_serving_config=featurestore_pb2.Featurestore.OnlineServingConfig(\n",
        "                fixed_node_count=3\n",
        "            ),\n",
        "        ),\n",
        "    )\n",
        ")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "57V8eVcB5VFZ"
      },
      "outputs": [],
      "source": [
        "# Wait for LRO to finish and get the LRO result.\n",
        "print(create_lro.result())"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "ag8pCQ7rNjVf"
      },
      "source": [
        "You can use [GetFeaturestore](https://cloud.google.com/vertex-ai/docs/reference/rpc/google.cloud.aiplatform.v1beta1#google.cloud.aiplatform.v1beta1.FeaturestoreService.GetFeaturestore) or [ListFeaturestores](https://cloud.google.com/vertex-ai/docs/reference/rpc/google.cloud.aiplatform.v1beta1#google.cloud.aiplatform.v1beta1.FeaturestoreService.ListFeaturestores) to check if the Featurestore was successfully created. The following example gets the details of the Featurestore.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "eKhD4q8rXjmM"
      },
      "outputs": [],
      "source": [
        "admin_client.get_featurestore(\n",
        "    name=admin_client.featurestore_path(PROJECT_ID, REGION, FEATURESTORE_ID)\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "EpmJq75zXjmT"
      },
      "source": [
        "### Create Entity Type\n",
        "You can specify a monitoring config which will by default be inherited by all Features under this EntityType."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "s9eZ7aJLXjmT"
      },
      "outputs": [],
      "source": [
        "# Create users entity type with monitoring enabled.\n",
        "# All Features belonging to this EntityType will by default inherit the monitoring config.\n",
        "users_entity_type_lro = admin_client.create_entity_type(\n",
        "    featurestore_service_pb2.CreateEntityTypeRequest(\n",
        "        parent=admin_client.featurestore_path(PROJECT_ID, REGION, FEATURESTORE_ID),\n",
        "        entity_type_id=\"users\",\n",
        "        entity_type=entity_type_pb2.EntityType(\n",
        "            description=\"Users entity\",\n",
        "            monitoring_config=featurestore_monitoring_pb2.FeaturestoreMonitoringConfig(\n",
        "                snapshot_analysis=featurestore_monitoring_pb2.FeaturestoreMonitoringConfig.SnapshotAnalysis(\n",
        "                    monitoring_interval=Duration(seconds=86400),  # 1 day\n",
        "                ),\n",
        "            ),\n",
        "        ),\n",
        "    )\n",
        ")\n",
        "\n",
        "# Similarly, wait for EntityType creation operation.\n",
        "print(users_entity_type_lro.result())"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "hJqNOttvOc2a"
      },
      "outputs": [],
      "source": [
        "# Create movies entity type without a monitoring configuration.\n",
        "movies_entity_type_lro = admin_client.create_entity_type(\n",
        "    featurestore_service_pb2.CreateEntityTypeRequest(\n",
        "        parent=admin_client.featurestore_path(PROJECT_ID, REGION, FEATURESTORE_ID),\n",
        "        entity_type_id=\"movies\",\n",
        "        entity_type=entity_type_pb2.EntityType(description=\"Movies entity\"),\n",
        "    )\n",
        ")\n",
        "\n",
        "# Similarly, wait for EntityType creation operation.\n",
        "print(movies_entity_type_lro.result())"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "FJW4q-0jO2Xf"
      },
      "source": [
        "### Create Feature\n",
        "\n",
        "You can also set a custom monitoring configuration at the Feature level, and view the properties and metrics in the console: sample [properties](https://storage.googleapis.com/cloud-samples-data/ai-platform-unified/datasets/featurestore/Feature%20Properties.png), sample [metrics](https://storage.googleapis.com/cloud-samples-data/ai-platform-unified/datasets/featurestore/Feature%20Snapshot%20Distribution.png)."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "ZJD7-6GFqc1z"
      },
      "outputs": [],
      "source": [
        "# Create features for the 'users' entity.\n",
        "# 'age' Feature leaves the monitoring config unset, which means it'll inherit the config from EntityType.\n",
        "# 'gender' Feature explicitly disables monitoring.\n",
        "# 'liked_genres' Feature is a STRING_ARRAY type, so it is automatically excluded from monitoring.\n",
        "# For Features with monitoring enabled, distribution statistics are updated periodically in the console.\n",
        "admin_client.batch_create_features(\n",
        "    parent=admin_client.entity_type_path(PROJECT_ID, REGION, FEATURESTORE_ID, \"users\"),\n",
        "    requests=[\n",
        "        featurestore_service_pb2.CreateFeatureRequest(\n",
        "            feature=feature_pb2.Feature(\n",
        "                value_type=feature_pb2.Feature.ValueType.INT64,\n",
        "                description=\"User age\",\n",
        "            ),\n",
        "            feature_id=\"age\",\n",
        "        ),\n",
        "        featurestore_service_pb2.CreateFeatureRequest(\n",
        "            feature=feature_pb2.Feature(\n",
        "                value_type=feature_pb2.Feature.ValueType.STRING,\n",
        "                description=\"User gender\",\n",
        "                monitoring_config=featurestore_monitoring_pb2.FeaturestoreMonitoringConfig(\n",
        "                    snapshot_analysis=featurestore_monitoring_pb2.FeaturestoreMonitoringConfig.SnapshotAnalysis(\n",
        "                        disabled=True,\n",
        "                    ),\n",
        "                ),\n",
        "            ),\n",
        "            feature_id=\"gender\",\n",
        "        ),\n",
        "        featurestore_service_pb2.CreateFeatureRequest(\n",
        "            feature=feature_pb2.Feature(\n",
        "                value_type=feature_pb2.Feature.ValueType.STRING_ARRAY,\n",
        "                description=\"An array of genres that this user liked\",\n",
        "            ),\n",
        "            feature_id=\"liked_genres\",\n",
        "        ),\n",
        "    ],\n",
        ").result()"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "tWx_wI_FS8tE"
      },
      "outputs": [],
      "source": [
        "# Create features for movies type.\n",
        "# 'title' Feature enables monitoring.\n",
        "admin_client.batch_create_features(\n",
        "    parent=admin_client.entity_type_path(PROJECT_ID, REGION, FEATURESTORE_ID, \"movies\"),\n",
        "    requests=[\n",
        "        featurestore_service_pb2.CreateFeatureRequest(\n",
        "            feature=feature_pb2.Feature(\n",
        "                value_type=feature_pb2.Feature.ValueType.STRING,\n",
        "                description=\"The title of the movie\",\n",
        "                monitoring_config=featurestore_monitoring_pb2.FeaturestoreMonitoringConfig(\n",
        "                    snapshot_analysis=featurestore_monitoring_pb2.FeaturestoreMonitoringConfig.SnapshotAnalysis(\n",
        "                        monitoring_interval=Duration(seconds=172800),  # 2 days\n",
        "                    ),\n",
        "                ),\n",
        "            ),\n",
        "            feature_id=\"title\",\n",
        "        ),\n",
        "        featurestore_service_pb2.CreateFeatureRequest(\n",
        "            feature=feature_pb2.Feature(\n",
        "                value_type=feature_pb2.Feature.ValueType.STRING,\n",
        "                description=\"The genres of the movie\",\n",
        "            ),\n",
        "            feature_id=\"genres\",\n",
        "        ),\n",
        "        featurestore_service_pb2.CreateFeatureRequest(\n",
        "            feature=feature_pb2.Feature(\n",
        "                value_type=feature_pb2.Feature.ValueType.DOUBLE,\n",
        "                description=\"The average rating for the movie, range is [1.0-5.0]\",\n",
        "            ),\n",
        "            feature_id=\"average_rating\",\n",
        "        ),\n",
        "    ],\n",
        ").result()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "xUVOzrAb1AFX"
      },
      "source": [
        "## Search created features\n",
        "\n",
        "While the [ListFeatures](https://cloud.google.com/vertex-ai/docs/reference/rpc/google.cloud.aiplatform.v1beta1#google.cloud.aiplatform.v1beta1.FeaturestoreService.ListFeatures) method allows you to easily view all features of a single\n",
        "entity type, the [SearchFeatures](https://cloud.google.com/vertex-ai/docs/reference/rpc/google.cloud.aiplatform.v1beta1#google.cloud.aiplatform.v1beta1.FeaturestoreService.SearchFeatures) method searches across all featurestores\n",
        "and entity types in a given location (such as `us-central1`). This can help you discover features that were created by someone else.\n",
        "\n",
        "You can query based on feature properties including feature ID, entity type ID,\n",
        "and feature description. You can also limit results by filtering on a specific\n",
        "featurestore, feature value type, and/or labels."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "Hs_7T_hs17ew"
      },
      "outputs": [],
      "source": [
        "# Search for all features across all featurestores.\n",
        "list(admin_client.search_features(location=BASE_RESOURCE_PATH))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "jcxsiBUiIyvE"
      },
      "source": [
        "Now, narrow down the search to features that are of type `DOUBLE`"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "a9ovJSyEI4OZ"
      },
      "outputs": [],
      "source": [
        "# Search for all features with value type `DOUBLE`\n",
        "list(\n",
        "    admin_client.search_features(\n",
        "        featurestore_service_pb2.SearchFeaturesRequest(\n",
        "            location=BASE_RESOURCE_PATH, query=\"value_type=DOUBLE\"\n",
        "        )\n",
        "    )\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Wtr9tvH6JAOY"
      },
      "source": [
        "Or, limit the search results to features with specific keywords in their ID and type."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "3G1mNV1uJFBC"
      },
      "outputs": [],
      "source": [
        "# Filter on feature value type and keywords.\n",
        "list(\n",
        "    admin_client.search_features(\n",
        "        featurestore_service_pb2.SearchFeaturesRequest(\n",
        "            location=BASE_RESOURCE_PATH, query=\"feature_id:title AND value_type=STRING\"\n",
        "        )\n",
        "    )\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "K3n5XdK8Xjmw"
      },
      "source": [
        "## Import Feature Values\n",
        "\n",
        "You need to import feature values before you can use them for online/offline serving. In this step, you will learn how to import feature values by calling the ImportFeatureValues API using the Python SDK.\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "BlqJ-QdTcs6W"
      },
      "source": [
        "### Source Data Format and Layout\n",
        "\n",
        "As mentioned above, BigQuery table/Avro/CSV are supported. No matter what format you are using, each imported entity *must* have an ID; also, each entity can *optionally* have a timestamp, sepecifying when the feature values are generated. This Colab uses Avro as an input, located at this public [bucket](https://pantheon.corp.google.com/storage/browser/cloud-samples-data/ai-platform-unified/datasets/featurestore;tab=objects?project=storage-samples&prefix=&forceOnObjectsSortingFiltering=false). The Avro schemas are as follows:\n",
        "\n",
        "**For the Users entity**:\n",
        "```\n",
        "schema = {\n",
        "  \"type\": \"record\",\n",
        "  \"name\": \"User\",\n",
        "  \"fields\": [\n",
        "      {\n",
        "       \"name\":\"user_id\",\n",
        "       \"type\":[\"null\",\"string\"]\n",
        "      },\n",
        "      {\n",
        "       \"name\":\"age\",\n",
        "       \"type\":[\"null\",\"long\"]\n",
        "      },\n",
        "      {\n",
        "       \"name\":\"gender\",\n",
        "       \"type\":[\"null\",\"string\"]\n",
        "      },\n",
        "      {\n",
        "       \"name\":\"liked_genres\",\n",
        "       \"type\":{\"type\":\"array\",\"items\":\"string\"}\n",
        "      },\n",
        "      {\n",
        "       \"name\":\"update_time\",\n",
        "       \"type\":[\"null\",{\"type\":\"long\",\"logicalType\":\"timestamp-micros\"}]\n",
        "      },\n",
        "  ]\n",
        " }\n",
        "```\n",
        "\n",
        "**For the Movies entity**\n",
        "```\n",
        "schema = {\n",
        " \"type\": \"record\",\n",
        " \"name\": \"Movie\",\n",
        " \"fields\": [\n",
        "     {\n",
        "      \"name\":\"movie_id\",\n",
        "      \"type\":[\"null\",\"string\"]\n",
        "     },\n",
        "     {\n",
        "      \"name\":\"average_rating\",\n",
        "      \"type\":[\"null\",\"double\"]\n",
        "     },\n",
        "     {\n",
        "      \"name\":\"title\",\n",
        "      \"type\":[\"null\",\"string\"]\n",
        "     },\n",
        "     {\n",
        "      \"name\":\"genres\",\n",
        "      \"type\":[\"null\",\"string\"]\n",
        "     },\n",
        "     {\n",
        "      \"name\":\"update_time\",\n",
        "      \"type\":[\"null\",{\"type\":\"long\",\"logicalType\":\"timestamp-micros\"}]\n",
        "     },\n",
        " ]\n",
        "}\n",
        "```"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "m7DyDa6chbJx"
      },
      "source": [
        "### Import feature values for Users\n",
        "\n",
        "When importing, specify the following in your request:\n",
        "\n",
        "*   Data source format: BigQuery Table/Avro/CSV\n",
        "*   Data source URL\n",
        "*   Destination: featurestore/entity types/features to be imported\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "RUhm6-yzXjmx"
      },
      "outputs": [],
      "source": [
        "import_users_request = featurestore_service_pb2.ImportFeatureValuesRequest(\n",
        "    entity_type=admin_client.entity_type_path(\n",
        "        PROJECT_ID, REGION, FEATURESTORE_ID, \"users\"\n",
        "    ),\n",
        "    avro_source=io_pb2.AvroSource(\n",
        "        # Source\n",
        "        gcs_source=io_pb2.GcsSource(\n",
        "            uris=[\n",
        "                \"gs://cloud-samples-data-us-central1/ai-platform-unified/datasets/featurestore/users.avro\"\n",
        "            ]\n",
        "        )\n",
        "    ),\n",
        "    entity_id_field=\"user_id\",\n",
        "    feature_specs=[\n",
        "        # Features\n",
        "        featurestore_service_pb2.ImportFeatureValuesRequest.FeatureSpec(id=\"age\"),\n",
        "        featurestore_service_pb2.ImportFeatureValuesRequest.FeatureSpec(id=\"gender\"),\n",
        "        featurestore_service_pb2.ImportFeatureValuesRequest.FeatureSpec(\n",
        "            id=\"liked_genres\"\n",
        "        ),\n",
        "    ],\n",
        "    feature_time_field=\"update_time\",\n",
        "    worker_count=10,\n",
        ")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "qwznuUiwjwJF"
      },
      "outputs": [],
      "source": [
        "# Start to import, will take a couple of minutes\n",
        "ingestion_lro = admin_client.import_feature_values(import_users_request)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "_sDl3ZcrF64T"
      },
      "outputs": [],
      "source": [
        "# Polls for the LRO status and prints when the LRO has completed\n",
        "ingestion_lro.result()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "laXdJPIqkLJO"
      },
      "source": [
        "### Import feature values for Movies\n",
        "\n",
        "Similarly, import feature values for 'movies' into the featurestore.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "-W1lCxgDl6iR"
      },
      "outputs": [],
      "source": [
        "import_movie_request = featurestore_service_pb2.ImportFeatureValuesRequest(\n",
        "    entity_type=admin_client.entity_type_path(\n",
        "        PROJECT_ID, REGION, FEATURESTORE_ID, \"movies\"\n",
        "    ),\n",
        "    avro_source=io_pb2.AvroSource(\n",
        "        gcs_source=io_pb2.GcsSource(\n",
        "            uris=[\n",
        "                \"gs://cloud-samples-data-us-central1/ai-platform-unified/datasets/featurestore/movies.avro\"\n",
        "            ]\n",
        "        )\n",
        "    ),\n",
        "    entity_id_field=\"movie_id\",\n",
        "    feature_specs=[\n",
        "        featurestore_service_pb2.ImportFeatureValuesRequest.FeatureSpec(id=\"title\"),\n",
        "        featurestore_service_pb2.ImportFeatureValuesRequest.FeatureSpec(id=\"genres\"),\n",
        "        featurestore_service_pb2.ImportFeatureValuesRequest.FeatureSpec(\n",
        "            id=\"average_rating\"\n",
        "        ),\n",
        "    ],\n",
        "    feature_time_field=\"update_time\",\n",
        "    worker_count=10,\n",
        ")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "Q-MATtpvm3HI"
      },
      "outputs": [],
      "source": [
        "# Start to import, will take a couple of minutes\n",
        "ingestion_lro = admin_client.import_feature_values(import_movie_request)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "VpaK3yRCnNnI"
      },
      "outputs": [],
      "source": [
        "# Polls for the LRO status and prints when the LRO has completed\n",
        "ingestion_lro.result()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "9TdxPYdDXjnA"
      },
      "source": [
        "## Online serving"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "ezJIMyU-XjnB"
      },
      "source": [
        "The\n",
        "[Online Serving APIs](https://cloud.google.com/vertex-ai/docs/reference/rpc/google.cloud.aiplatform.v1beta1#featurestoreonlineservingservice)\n",
        "lets you serve feature values for small batches of entities. It's designed for latency-sensitive service, such as online model prediction. For example, for a movie service, you might want to quickly shows movies that the current user would most likely watch by using online predictions."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "foNB0D2aw37c"
      },
      "source": [
        "### Read one entity per request\n",
        "\n",
        "The ReadFeatureValues API is used to read feature values of one entity; hence\n",
        "its custom HTTP verb is `readFeatureValues`. By default, the API will return the  latest value of each feature, meaning the feature values with the most recent  timestamp.\n",
        "\n",
        "To read feature values, specify the entity ID and features to read. The response\n",
        "contains a `header` and an `entity_view`. Each row of data in the `entity_view`\n",
        "contains one feature value, in the same order of features as listed in the response header."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "3rfWqLrbXjnJ"
      },
      "outputs": [],
      "source": [
        "# Fetch the following 3 features.\n",
        "feature_selector = FeatureSelector(\n",
        "    id_matcher=IdMatcher(ids=[\"age\", \"gender\", \"liked_genres\"])\n",
        ")\n",
        "\n",
        "data_client.read_feature_values(\n",
        "    featurestore_online_service_pb2.ReadFeatureValuesRequest(\n",
        "        # Fetch from the following feature store/entity type\n",
        "        entity_type=admin_client.entity_type_path(\n",
        "            PROJECT_ID, REGION, FEATURESTORE_ID, \"users\"\n",
        "        ),\n",
        "        # Fetch the user features whose ID is \"alice\"\n",
        "        entity_id=\"alice\",\n",
        "        feature_selector=feature_selector,\n",
        "    )\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "oYk83Zt9xF8m"
      },
      "source": [
        "### Read multiple entities per request\n",
        "\n",
        "To read feature values from multiple entities, use the\n",
        "StreamingReadFeatureValues API, which is almost identical to the previous\n",
        "ReadFeatureValues API. Note that fetching only a small number of entities is recomended when using this API due to its latency-sensitive nature."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "BIJFcIIHULOd"
      },
      "outputs": [],
      "source": [
        "# Read the same set of features as above, but for multiple entities.\n",
        "response_stream = data_client.streaming_read_feature_values(\n",
        "    featurestore_online_service_pb2.StreamingReadFeatureValuesRequest(\n",
        "        entity_type=admin_client.entity_type_path(\n",
        "            PROJECT_ID, REGION, FEATURESTORE_ID, \"users\"\n",
        "        ),\n",
        "        entity_ids=[\"alice\", \"bob\"],\n",
        "        feature_selector=feature_selector,\n",
        "    )\n",
        ")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "NFrVLiHyUj2l"
      },
      "outputs": [],
      "source": [
        "# Iterate and process response. Note the first one is always the header only.\n",
        "for response in response_stream:\n",
        "    print(response)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Sds42j8ZsCzS"
      },
      "source": [
        "Now that you have learned how to featch imported feature values for online serving, the next step is learning how to use imported feature values for offline use cases."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "WpvhPAYxD-Ml"
      },
      "source": [
        "## Batch Serving\n",
        "\n",
        "Batch Serving is used to fetch a large batch of feature values for high-throughput, typically for training a model or batch prediction. In this section, you will learn how to prepare for training examples by calling the BatchReadFeatureValues API."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "tPzAGvqJHh3B"
      },
      "source": [
        "### Use case\n",
        "\n",
        "**The task** is to prepare a training dataset to train a model, which predicts if a given user will watch a given movie. To achieve this, you need 2 sets of input:\n",
        "\n",
        "*   Features: you already imported into the featurestore.\n",
        "*   Labels: the groud-truth data recorded that user X has watched movie Y.\n",
        "\n",
        "\n",
        "To be more specific, the ground-truth observation is described in Table 1 and the desired training dataset is described in Table 2. Each row in Table 2 is a result of joining the imported feature values from Feature Store according to the entity IDs and timestamps in Table 1. In this example,  the `age`, `gender` and `liked_genres` features from `users` and\n",
        "the `genres` and `average_rating` features from `movies` are chosen to train the model. Note that only positive examples are shown in these 2 tables, i.e., you can imagine there is a label column whose values are all `True`.\n",
        "\n",
        "BatchReadFeatureValues API takes Table 1 as\n",
        "input, joins all required feature values from the featurestore, and returns Table 2 for training.\n",
        "\n",
        "<h4 align=\"center\">Table 1. Ground-truth Data</h4>\n",
        "\n",
        "users | movies | timestamp            \n",
        "----- | -------- | -------------------- \n",
        "alice  | Cinema Paradiso     | 2019-11-01T00:00:00Z \n",
        "bob  | The Shining     | 2019-11-15T18:09:43Z \n",
        "...   | ...      | ...     \n",
        "\n",
        "\n",
        "<h4 align=\"center\">Table 2. Expected Training Data Generated by Batch Read API (Positive Samples)</h4>\n",
        "\n",
        "timestamp            | entity_type_users | age | gender | liked_genres | entity_type_movies | genres | average_rating  \n",
        "-------------------- | ----------------- | --------------- | ---------------- | -------------------- | -------- | --------- | ----- \n",
        "2019-11-01T00:00:00Z | bob              | 35        | M                | [Action, Crime]                 | The Shining | Horror | 4.8 \n",
        "2019-11-01T00:00:00Z | alice             | 55        | F                | [Drama, Comedy]                 | Cinema Paradiso | Romance | 4.5 \n",
        "... | ... | ... | ... | ... | ... | ... | ... \n",
        "             "
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "hKwWGg2i4a4G"
      },
      "source": [
        "#### Why timestamp?\n",
        "\n",
        "Note that there is a `timestamp` column in Table 2. This indicates the time when the ground-truth was observed. This is to avoid data inconsistency.\n",
        "\n",
        "For example, the 1st row of Table 2 indicates that user `alice` watched movie `Cinema Paradiso` on `2019-11-01T00:00:00Z`. The featurestore keeps feature values for all timestamps but fetches feature values *only* at the given timestamp during batch serving. On 2019-11-01 alice might be 54 years old, but now alice might be 56; featurestore returns `age=54` as alice's age, instead of `age=56`, because that is the value of the feature at the observation time. Similarly, other features might be time-variant as well, such as liked_genres."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "W8dLJ9nuDFgI"
      },
      "source": [
        "### Batch Read Feature Values\n",
        "\n",
        "Assemble the request which specify the following info:\n",
        "\n",
        "*   Where is the label data, i.e., Table 1.\n",
        "*   Which features are read, i.e., the column names in Table 2.\n",
        "\n",
        "The output is stored in a BigQuery table.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "7IyoXHY2ECnh"
      },
      "outputs": [],
      "source": [
        "batch_serving_request = featurestore_service_pb2.BatchReadFeatureValuesRequest(\n",
        "    # featurestore info\n",
        "    featurestore=admin_client.featurestore_path(PROJECT_ID, REGION, FEATURESTORE_ID),\n",
        "    # URL for the label data, i.e., Table 1.\n",
        "    csv_read_instances=io_pb2.CsvSource(\n",
        "        gcs_source=io_pb2.GcsSource(uris=[INPUT_CSV_FILE])\n",
        "    ),\n",
        "    destination=featurestore_service_pb2.FeatureValueDestination(\n",
        "        bigquery_destination=io_pb2.BigQueryDestination(\n",
        "            # Output to BigQuery table created earlier\n",
        "            output_uri=DESTINATION_TABLE_URI\n",
        "        )\n",
        "    ),\n",
        "    entity_type_specs=[\n",
        "        featurestore_service_pb2.BatchReadFeatureValuesRequest.EntityTypeSpec(\n",
        "            # Read the 'age', 'gender' and 'liked_genres' features from the 'users' entity\n",
        "            entity_type_id=\"users\",\n",
        "            feature_selector=FeatureSelector(\n",
        "                id_matcher=IdMatcher(\n",
        "                    ids=[\n",
        "                        # features, use \"*\" if you want to select all features within this entity type\n",
        "                        \"age\",\n",
        "                        \"gender\",\n",
        "                        \"liked_genres\",\n",
        "                    ]\n",
        "                )\n",
        "            ),\n",
        "        ),\n",
        "        featurestore_service_pb2.BatchReadFeatureValuesRequest.EntityTypeSpec(\n",
        "            # Read the 'average_rating' and 'genres' feature values of the 'movies' entity\n",
        "            entity_type_id=\"movies\",\n",
        "            feature_selector=FeatureSelector(\n",
        "                id_matcher=IdMatcher(ids=[\"average_rating\", \"genres\"])\n",
        "            ),\n",
        "        ),\n",
        "    ],\n",
        ")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "bZO5sRCfEEWn"
      },
      "outputs": [],
      "source": [
        "# Execute the batch read\n",
        "batch_serving_lro = admin_client.batch_read_feature_values(batch_serving_request)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "ouMiJqh-EFlh"
      },
      "outputs": [],
      "source": [
        "# This long runing operation will poll until the batch read finishes.\n",
        "batch_serving_lro.result()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "3RAdjahHQ93J"
      },
      "source": [
        "After the LRO finishes, you should be able to see the result from the [BigQuery console](https://console.cloud.google.com/bigquery), in the dataset created earlier."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "TpV-iwP9qw9c"
      },
      "source": [
        "## Cleaning up\n",
        "\n",
        "To clean up all Google Cloud resources used in this project, you can [delete the Google Cloud\n",
        "project](https://cloud.google.com/resource-manager/docs/creating-managing-projects#shutting_down_projects) you used for the tutorial.\n",
        "\n",
        "You can also keep the project but delete the featurestore:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "a2WfqhbFzQBF"
      },
      "outputs": [],
      "source": [
        "admin_client.delete_featurestore(\n",
        "    request=featurestore_service_pb2.DeleteFeaturestoreRequest(\n",
        "        name=admin_client.featurestore_path(PROJECT_ID, REGION, FEATURESTORE_ID),\n",
        "        force=True,\n",
        "    )\n",
        ").result()\n",
        "client.delete_dataset(\n",
        "    DESTINATION_DATA_SET, delete_contents=True, not_found_ok=True\n",
        ")  # Make an API request.\n",
        "\n",
        "print(\"Deleted dataset '{}'.\".format(DESTINATION_DATA_SET))"
      ]
    }
  ],
  "metadata": {
    "colab": {
      "collapsed_sections": [
        "ze4-nDLfK4pw"
      ],
      "name": "gapic-feature-store.ipynb",
      "toc_visible": true
    },
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
